package com.gabry.dep;

import org.objectweb.asm.ClassAdapter;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.IllegalClassFormatException;
import java.security.ProtectionDomain;

/**
 * Created by ShaoJie.Wu on 2017/1/12 8:49.
 * 功能：
 * <p>
 * 备注：
 */
public class DepTransformer implements ClassFileTransformer {
    public byte[] transform(ClassLoader loader, String className, Class<?> classBeingRedefined,
                            ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
        try {
            ClassReader reader = new ClassReader(classfileBuffer);
            ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
            ClassAdapter adapter = new DepClassAdapter(writer, className);
            reader.accept(adapter, 0);
            // 生成新类字节码
            return writer.toByteArray();
        } catch (Throwable e) {
            e.printStackTrace();
            // 返回旧类字节码
            return classfileBuffer;
        }
    }
}